package com.romotc.common;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.RandomUtils;

import com.sun.org.apache.xml.internal.security.Init;

/**
 * 浏览器版本信息工具类
 * @author romotc
 *
 */
public class UserAgentUtil {

	/**
	 * 数据文件位置
	 */
	private String userAgentDBFile = "conifg" + File.separator + "UserAgents.txt";
	private List<String> agentList;
	private static UserAgentUtil instance;
	public static UserAgentUtil getInstance() {
		if(instance == null)
			instance = new UserAgentUtil();
		return instance;
	}
	
	public UserAgentUtil(String dbPath) {
		this.userAgentDBFile = dbPath;
		init();
	}
	
	public UserAgentUtil() {
		init();
	}
	
	/**
	 * 加载数据
	 */
	private void init() {
		File file = new File(userAgentDBFile);
		if(!file.exists()) {
			System.err.println("UserAgent数据文件不存在:" + userAgentDBFile);
			System.exit(0);
		}
		
		agentList = new ArrayList<String>();
		try {
			List<String> lines = FileUtils.readLines(file);
			for(String line : lines) {
				if(StringUtils.isNotBlank(line) && line.length() > 10) {
					agentList.add(line.trim());
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	public String getRandomUserAgent() {
		if(agentList.isEmpty())
			return null;
		
		return agentList.get(RandomUtils.nextInt(agentList.size()));
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String l = UserAgentUtil.getInstance().getRandomUserAgent();
		System.out.println(l);

	}

}
